package com.globant.dashboard.persist;

import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.globant.dashboard.model.Language;
import com.globant.dashboard.model.Role;
import com.globant.dashboard.model.User;

public class HibernateSessionFactory {
	
	private final String mySql="mySql";
	private final String hSql="hSql";
	
	private SessionFactory sessionFactory;

	/**
	 *  
	 */
	public void getMySqlSessionFactory(){
		
		Properties mySqlProperties= new Properties();
		
		mySqlProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		mySqlProperties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
		mySqlProperties.setProperty("hibernate.connection.url", "jdbc:mysql://localhost/test");
		mySqlProperties.setProperty("hibernate.connection.username", "");
		mySqlProperties.setProperty("hibernate.connection.password", "");
		mySqlProperties.setProperty("hibernate.order_updates", "true");
		mySqlProperties.setProperty("hibernate.hbm2ddl.auto", "update");
		mySqlProperties.setProperty("hibernate.connection.pool_size", "1");
		mySqlProperties.setProperty("hibernate.show_sql", "true");
		
		AnnotationConfiguration cfgMySql = new AnnotationConfiguration();
		cfgMySql.addAnnotatedClass(User.class)
				.addAnnotatedClass(Language.class).addAnnotatedClass(Role.class);
		cfgMySql.setProperties(mySqlProperties);

		this.sessionFactory=cfgMySql.buildSessionFactory();
		
		
	}
	
	public void getHSqlSessionFactory(){
		
		Properties hSqlProperties= new Properties();
		
		hSqlProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
		hSqlProperties.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
		hSqlProperties.setProperty("hibernate.connection.url", "jdbc:hsqldb:test/dashboard");
		hSqlProperties.setProperty("hibernate.connection.username", "sa");
		hSqlProperties.setProperty("hibernate.connection.password", "");
		hSqlProperties.setProperty("hibernate.order_updates", "true");
		hSqlProperties.setProperty("hibernate.hbm2ddl.auto", "update");
		hSqlProperties.setProperty("hibernate.connection.pool_size", "1");
		hSqlProperties.setProperty("hibernate.show_sql", "true");
	
		AnnotationConfiguration cfgHSql = new AnnotationConfiguration();
		cfgHSql.addAnnotatedClass(User.class)
				.addAnnotatedClass(Language.class).addAnnotatedClass(Role.class);
		cfgHSql.setProperties(hSqlProperties);
		
		this.sessionFactory=cfgHSql.buildSessionFactory();
	
	}
	
	public Session openSession() {
		
		String db=mySql; // Select between MySql or HSql database
		
		if(sessionFactory==null){
			if (db.equals(mySql)) getMySqlSessionFactory();
			else if (db.equals(hSql)) getHSqlSessionFactory();				
		}
		return sessionFactory.openSession();
	}
	

}
